package com.example.pceb.controller;

import com.example.pceb.VO.LoginVO;
import com.example.pceb.result.Result;
import com.example.pceb.service.UserService;
import com.example.pceb.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import com.example.pceb.entity.School;
import com.example.pceb.mapper.SchoolMapper;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    private SchoolMapper schoolMapper;

    //登录接口
    @PostMapping("/login")
    public Result<String> login( @RequestBody LoginVO loginVO) {
        return userService.loginByUserName(loginVO.getUsername(), loginVO.getPassword(), loginVO.getIdentity());
    }

    //获取用户信息
    @GetMapping("/user/info")
    public Result<Object> getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        return userService.getUserInfo(token);
    }

    //更新用户信息
    @PostMapping("/user/update")
    public Result<Object> updateUserInfo(HttpServletRequest request, @RequestBody Object userData) {
        String token = request.getHeader("Authorization");
        return userService.updateUserInfo(token, userData);
    }

    //Token验证接口
    @GetMapping("/token")
    public Result<String> loginByToken(String token) {
        return userService.loginByToken(token);
    }

    //注册接口
    @PostMapping("/register")
    public Result<String> register(@RequestBody LoginVO loginVO) {
        return userService.register(loginVO);
    }

    // 头像上传接口，支持学生和管理员
    @PostMapping("/user/uploadAvatar")
    public Result<String> uploadAvatar(@RequestHeader("Authorization") String token,
                                       @RequestParam("file") MultipartFile file) {
        // 解析token获取identity和username
        String identity = null;
        String username = null;
        try {
            String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            io.jsonwebtoken.Claims claims = com.example.pceb.utils.JwtUtil.parseToken(realToken);
            identity = claims.get("identity", String.class);
            username = claims.get("username", String.class);
        } catch (Exception e) {
            return Result.error("Token无效或已过期");
        }
        return userService.uploadAvatar(token, identity, username, file);
    }

    // 获取所有学校列表
    @GetMapping("/school/list")
    public Result<List<School>> getAllSchools() {
        List<School> schools = schoolMapper.selectList(null);
        return Result.success(schools);
    }
}
